class h_score {

	async updateStuScoreData(userId, stuCredit, stuGPA, scoreList, certScoreList) {
		try {
			//更新到缓存
			await this.redis.cache.set(`score@student@${userId}`, {stuCredit, stuGPA, scoreList, certScoreList, syncTime: this.common.timestamp()}, this.config.frame.sessionExpires.score)
			const scoreId = this.crypto.md5(`score${userId}`)
			const result = await this.mysql.cxxy.select({
				table: 'score',
				field: 'scoreId',
				where: 'scoreId=$scoreId',
				data: {
					scoreId
				}
			})
			console.log('存在', result)
			await this.mysql.cxxy.trans()
			if(!result[0]) {
				await this.mysql.cxxy.insert({
					table: 'score',
					field: [
						'scoreId',
						'stuCredit',
						'stuGPA',
						'scoreList',
						'certScoreList',
						'scoreDate'
					],
					data: {
						scoreId,
						stuCredit,
						stuGPA,
						scoreList: JSON.stringify(scoreList),
						certScoreList: JSON.stringify(certScoreList),
						scoreDate: parseInt(Date.now() / 1000)
					}
				})
				await this.mysql.cxxy.update({
					table: 'student',
					field: 'stuScoreId=$stuScoreId',
					where: 'userId=$userId',
					data: {
						stuScoreId: scoreId,
						userId
					}
				})
				await this.mysql.cxxy.cmt()
				return
			}
			await this.mysql.cxxy.update({
				table: 'score',
				field: [
					'stuCredit=$stuCredit',
					'stuGPA=$stuGPA',
					'scoreList=$scoreList',
					'certScoreList=$certScoreList',
					'scoreDate=$scoreDate'
				],
				where: 'scoreId=$scoreId',
				data: {
					stuCredit,
					stuGPA,
					scoreList: JSON.stringify(scoreList),
					certScoreList: JSON.stringify(certScoreList),
					scoreDate: parseInt(Date.now() / 1000),
					scoreId
				}
			})
			await this.mysql.cxxy.cmt()
			return scoreId
		}
		catch(err) {
			console.error(err)
			this.common.writeLog('error', `update student ${userId} score data failed`)
			return this.reject('-3039', 'update student score data failed')
		}
	}

	async getStuScoreCache(userId) {
		let scoreData = await this.redis.cache.get(`score@student@${userId}`, true)
		if(scoreData)
			return scoreData
		const result = await this.mysql.cxxy.select({
			table: [
				'student s',
				'score c'
			],
			field: [
				'c.stuCredit',
				'c.stuGPA',
				'c.scoreList',
				'c.certScoreList'
			],
			where: 's.stuScoreId=c.scoreId && s.userId=$userId',
			data: {
				userId
			}
		})
		if(result && result[0] && !isNaN(result[0].stuCredit) && !isNaN(result[0].stuGPA) && result[0].scoreList && result[0].certScoreList) {
			const {stuCredit, stuGPA, scoreList, certScoreList} = result[0]
			scoreData = {
				stuCredit,
				stuGPA,
				scoreList,
				certScoreList
			}
			await this.redis.cache.set(`score@student@${userId}`, scoreData, this.config.frame.sessionExpires.score)
			return scoreData
		}
		return false
	}

	//清除学生成绩缓存
	async clearStuScoreCache(userId) {
		return await this.redis.cache.delete(`score@student@${userId}`)
	}

	async getStuScore(user) {
		if(!this.hd.zf.checkZfLogin(user))
			return this.reject('-3007', 'zf user not logined in')
		const {userId, session} = user.data.zf
		let cookie = {}
		cookie[this.config.zf.url] = {
			'ASP.NET_SessionId': session
		}
		const result = await this.common.reqPost({
			url: `${this.config.zf.url}xscj_gc.aspx`,
			cookie,
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
				Referer:  `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			getData: {
				xh: userId,
				gnmkdm: 'N121605'
			},
			data: {
				__VIEWSTATE: this.config.zf.viewState.score,
				ddlXN: '',
				ddlXQ: '',
				Button2: '在校学习成绩查询'
			},
			getStatus: true
		})
		const {status, data} = result
		if(status.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		console.log(data)
		let $ = this.common.parseHTML(data)
		let scoreList = {}
		let temp = $('#xftj').children('b').text().trim().match(/获得学分(.+)；重修学分/)
		const stuCredit = (!temp || !temp[1] || isNaN(temp[1])) ? -1 : parseInt(temp[1] * 100)
		temp = $('#pjxfjd').children('b').text().trim().match(/平均学分绩点：(.+)/)
		const stuGPA = (!temp || !temp[1] || isNaN(temp[1])) ? -1 : parseInt(temp[1] * 100)
		$('#Datagrid1 tbody tr').each(function(index) {
			if(index == 0)
				return
			const item = $(this).children('td')
			const courseYear = item.eq(0).text().trim()
			const courseTerm = item.eq(1).text().trim()
			if(courseYear.length == 0 || courseTerm.length == 0)
				return
			if(!scoreList[courseYear])
				scoreList[courseYear] = {}
			if(!scoreList[courseYear][courseTerm])
				scoreList[courseYear][courseTerm] = []
			let courseScore = item.eq(8).text().trim()

			//补考成绩替代成绩处理
			let makeUpScore = item.eq(10).text().trim()
			if(makeUpScore.length > 0) {
				courseScore = makeUpScore
			}

			//重修成绩替代成绩处理
			let rebuildScore = item.eq(11).text().trim()
			if(rebuildScore.length > 0) {
				courseScore = rebuildScore
			}

			//处理多样化的成绩格式
			if(isNaN(courseScore)) {
				const index = ['优秀', '良好', '中等', '差', '及格', '合格', '不合格'].indexOf(courseScore)
				courseScore = ['great','good', 'medium', 'bad', 'pass', 'qualified', 'unqualified'][index]
				if(!courseScore)
					courseScore = 'unknown'
			}
			else
				courseScore = parseInt(parseFloat(courseScore) * 100)

			//课程学分
			const temp2 = item.eq(6).text().trim()
			const courseCredit = temp2 ? parseInt(parseFloat(temp2) * 100) : 0

			scoreList[courseYear][courseTerm].push({
				courseName: item.eq(3).text().trim(),
				courseType: ['必修课', '公选课', '拓展课'].indexOf(item.eq(4).text().trim()),
				courseCredit,
				courseScore
			})

		})
		console.log(`student credit:${stuCredit},gpa:${stuGPA},score is `, scoreList)
		const scoreData = {
			stuCredit,
			stuGPA,
			scoreList
		}
		return scoreData
	}

	async getStuCertScore(user) {
		if(!this.hd.zf.checkZfLogin(user))
			return this.reject('-3007', 'zf user not logined in')
		const {userId, session} = user.data.zf
		let cookie = {}
		cookie[this.config.zf.url] = {
			'ASP.NET_SessionId': session
		}
		const result = await this.common.reqGet({
			url: `${this.config.zf.url}xsdjkscx.aspx`,
			cookie,
			headers: {
				Referer:  `${this.config.zf.url}xs_main.aspx?xh=${userId}`
			},
			data: {
				xh: userId,
				gnmkdm: 'N121606'
			},
			getStatus: true
		})
		const {status, data} = result
		if(status.code != 200) {
			await this.hd.zf.zfLogout(user)
			return this.reject('-3003', 'zf resources not found')
		}
		let $ = this.common.parseHTML(data)
		let certScoreList = {}
		$('#DataGrid1 tbody tr').each(function(index) {
			if(index ==  0)
				return
			const item = $(this).children('td')
			const courseYear = item.eq(0).text().trim()
			const courseTerm = item.eq(1).text().trim()
			if(!certScoreList[courseYear])
				certScoreList[courseYear] = {}
			if(!certScoreList[courseYear][courseTerm])
				certScoreList[courseYear][courseTerm] = []
			certScoreList[courseYear][courseTerm].push({
				certName: item.eq(2).text().trim(),
				examId: item.eq(3).text().trim(),
				examDate: item.eq(4).text().trim(),
				examScore: parseInt(parseFloat(item.eq(5).text().trim()) * 100),
			})
		})
		console.log(`student cert score is `, certScoreList)
		return certScoreList
	}

}

module.exports = h_score